package basic.chapter5;

/**
 * @author Kevin
 * @date 2020/2/21 14:22
 */
public class Account2 {
    private int id;
    private int balance;
    // 转账
    void transfer(Account2 target, int amt){
        Account2 left = this;        //①
        Account2 right = target;    //②
        if (this.id > target.id) { //③
            left = target;           //④
            right = this;            //⑤
        }                          //⑥
        // 锁定序号小的账户
        synchronized(left){
            // 锁定序号大的账户
            synchronized(right){
                if (this.balance > amt){
                    this.balance -= amt;
                    target.balance += amt;
                }
            }
        }
    }
}
